package com.example.zookeeper.demo;

import com.example.zookeeper.core.ZkCore;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class PersistenceWatcherDemo
{
    private final ZkCore zkCore;

    @Autowired
    public PersistenceWatcherDemo(ZkCore zkCore)
    {
        this.zkCore = zkCore;
    }

    /**
     * 链接zookeeper
     * 创建节点
     * 获取节点数据
     * 持久性监控节点数据变化，并且打印出变化后节点值
     */
    public void start()
    {
        String path = "/test";
        try
        {
            if (zkCore.exist(path) == null)
            {
                zkCore.createNode("/test", "hello zookeeper".getBytes(), CreateMode.EPHEMERAL);
            }
            else
            {
                System.out.println("node: " + path + " has exist");
            }
            String value = getValue(zkCore, path);
            System.out.println("value: " + value);
        } catch (KeeperException | InterruptedException e)
        {
            e.printStackTrace();
        }
    }

    private static String getValue(ZkCore zkCore, String path) throws KeeperException, InterruptedException
    {
        byte[] data = zkCore.getValue(path, watchedEvent ->
        {
            try
            {
                String value = getValue(zkCore, path);
                System.out.println("value: " + value);
            } catch (KeeperException | InterruptedException e)
            {
                e.printStackTrace();
            }
        });
        return new String(data);
    }

    public void close()
    {
        try
        {
            zkCore.close();
        } catch (InterruptedException e)
        {
            e.printStackTrace();
        }
    }
}
